/*
 * Soldier.cpp
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "Soldier.h"
#include "Ship.h"
#include "Images.h"
#include "Missile.h"

#define WEAPON_SPEED -8

Soldier::Soldier(int x, int y, const SDL_Rect& area)
    : Sprite(Images::get(Images::SOLDIER)),
      _state(READY),
      _area(area),
      _inertion(30),
      _dx(1)
{
    _rect.x = x;
    _rect.y = y;
}

bool Soldier::update(void* arg)
{
    Ship* ship = reinterpret_cast<Ship*>(arg);

    if (_rect.y > _area.h)
        _rect.y = -_rect.h;

    Missile* missile = ship->missiles().collide(_rect);
    if (missile)
    {
        if (missile->is_ready())
            ship->damage(1);
        missile->explode(this);
        return is_alive();
    }

    if (collides(ship->rect()))
    {
        damage(1);
        ship->damage(1);
        return is_alive();
    }

    switch (_state)
    {
    case READY:
        break;
    case ATTACKING:
        attack_target(ship);
        break;
    };

    return is_alive();
}

int Soldier::damage(int amount)
{
    _state = EXPLODING;
    return 1;
}

void Soldier::attack(Ship* ship)
{
    _state = ATTACKING;
}

void Soldier::attack_target(Ship* ship)
{
    _inertion.tick();
    _rect.x += _dx;
    ++_rect.y;

    if (_rect.x == ship->x())
        _inertion.restart();

    if (_inertion.hit())
    {
        if (_rect.x < ship->x())
            _dx = 1;
        else
            _dx = -1;
    }
}

